﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System.Threading;
using System.ServiceModel;

using MINERP.BLL.UserLogin;
using MINERP.ComControls;
using MINERP.COM;

using System.Runtime.InteropServices;
using System.ServiceModel.Configuration;
using System.Text.RegularExpressions;

namespace MINERP.UserLogin
{
    public partial class FrmLogin : Form
    {

        private FrmMain _frmMain = null;
        private UserLoginBLL _userLoginBLL = new UserLoginBLL();
        private string _sqlDatebase = string.Empty;
        private List<Control> _controls = new List<Control>();
        private List<string> _listServer = new List<string>(); //数据库服务器列表
        private List<string> _controlName = new List<string>();
        private Dictionary<int, string> _techName = new Dictionary<int, string>();
        private string _assemblyName = string.Empty;
        private string _className = string.Empty;
        private string _headPicPath = string.Empty;
        List<string> _list = null;

        //private 


        private const int HWND_TOPMOST = -1;//                        ' 窗口在前 
        private const int HWND_NOTOPMOST = -2;



        public FrmLogin()
        {
            FindWindow();
            InitializeComponent();
        }
        public FrmLogin(List<string> list)
        {
            FindWindow();
            InitializeComponent();
            _list = list;
        }

        public FrmLogin(string strServerNameAndIP)
        {
            InitializeComponent();
            cmbServer.Text = strServerNameAndIP;
        }

        //单件生成本Form实例
        private static FrmLogin _instance = null;
        public static FrmLogin GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new FrmLogin();
                }
                return _instance;
            }
            set
            {
                _instance = value;
            }
        }

        #region 登录
        //登录
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUser.Text == string.Empty)
                {
                    txtUser.Focus();
                    //MessageBox.Show("用户账号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ErrrProvider1.SetError(txtUser, "用户账号不能为空");
                    return;
                }
                if (txtPwd.Text == string.Empty)
                {
                    txtPwd.Focus();
                    //MessageBox.Show("用户密码不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ErrrProvider1.SetError(txtPwd, "用户密码不能为空");
                    return;
                }
                ErrrProvider1.ClearErrors();
                _userLoginBLL.IsUserPass(txtUser.Text.Trim(), MD5HashCode.GetHash(txtPwd.Text.Trim()));

                this.Hide();
                FrmMain.LoginName = txtUser.Text.Trim();
                FrmMain.PWD = MD5HashCode.GetHash(txtPwd.Text.Trim());
                _frmMain = FrmMain.GetInstance;
                _frmMain.Show(this);

                txtUser.Text = string.Empty;
                txtPwd.Text = string.Empty;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示");
                return;
            }

        }

        #endregion

        //退出程序
        private void btnQuit_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }
        private void frmLogin_Load(object sender, EventArgs e)
        {
            Application.ApplicationExit += new EventHandler(Restart);
            string connstr = ConfigurationManager.ConnectionStrings["newSampleYPDBEntities"].ToString();
            SetLoadInfo(connstr);
            GetServerInfo(connstr);
        }


        //默认重启
        private void Restart(object sender, EventArgs e)
        {

            if (_serverChange)
            {
                Process.Start(Application.ExecutablePath);
            }
        }
        private void SetLoadInfo(string connstr)
        {
            string aa = connstr.Substring(connstr.IndexOf("Data Source="));
            string[] b = aa.Split(new Char[] { ';' });
            string strServer = b[0].ToString();   //--服务器名称
            string sqlServer = strServer.Substring(12);
            string strDatabase = b[1].ToString(); //--数据库名字
            string SqlDatebase = strDatabase.Substring(16);
            cmbServer.Text = sqlServer + "(" + SqlDatebase + ")";
        }
        //获取默认数据库连接信息
        public void GetServerInfo(string Connstr)
        {
            string aa = Connstr.Substring(Connstr.IndexOf("Data Source="));
            string[] b = aa.Split(new Char[] { ';' });
            string strServer = b[0].ToString();   //--服务器名称
            string sqlServer = strServer.Substring(12);
            string strDatabase = b[1].ToString(); //--数据库名字
            string SqlDatebase = strDatabase.Substring(16);
            if (this.lblServerName.Text.ToLower() == sqlServer.ToLower() && this.lblDatabaseName.Text.ToLower() == SqlDatebase.ToLower())
            {
                IsNeedReStart = false;
            }
            else
            {
                IsNeedReStart = true;
            }

            if (sqlServer != null)
            {
                this.lblServerName.Text = sqlServer;
            }
            else
            {
                this.lblServerName.Text = string.Empty;
            }

            if (SqlDatebase != null)
            {
                this.lblDatabaseName.Text = SqlDatebase;
            }
            else
            {
                this.lblDatabaseName.Text = string.Empty;
            }

        }
        //修改连接配置
        private void ModifyConfig(string strConn)
        {
            //修改fffff
            //ConnectionStringSettings mySettings1 = new ConnectionStringSettings("fffff", strConn, "System.Data.SqlClient");
            //System.Configuration.Configuration config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //config1.ConnectionStrings.ConnectionStrings.Remove("fffff");
            //config1.ConnectionStrings.ConnectionStrings.Add(mySettings1);
            //config1.Save(ConfigurationSaveMode.Minimal);
            //ConfigurationManager.RefreshSection("ConnectionStrings");


            //修改sqlCon

            ConnectionStringSettings mySettings3 = new ConnectionStringSettings("sqlCon", strConn, "System.Data.SqlClient");
            System.Configuration.Configuration config3 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config3.ConnectionStrings.ConnectionStrings.Remove("sqlCon");
            config3.ConnectionStrings.ConnectionStrings.Add(mySettings3);
            config3.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("ConnectionStrings");

            //修改ENTITY
            string connectionString = ConfigurationManager.ConnectionStrings["newSampleYPDBEntities"].ToString();
            string strConn1 = strConn + ";";
            string strConn2 = string.Empty;
            strConn2 = connectionString.Substring(connectionString.IndexOf("MultipleActiveResultSets"));
            string str = connectionString.Substring(0, connectionString.IndexOf("Data Source"));
            connectionString = str + strConn1 + strConn2;
            ConnectionStringSettings mySettings = new ConnectionStringSettings("newSampleYPDBEntities", connectionString, "System.Data.EntityClient");
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Remove("newSampleYPDBEntities");
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            config.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }

        /// <summary>
        /// udp 获取数据库服务器信息
        /// </summary>
        private List<string> GetServerInfo()
        {
            int recv = 0;
            byte[] data = new byte[1024];
            List<string> list = new List<string>();

            //构建TCP 服务器

            //得到本机IP，设置TCP端口号         
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8001);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            newsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
            //绑定网络地址
            newsock.Bind(ipep);
            //得到客户机IP
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)(sender);
            string strTemp = string.Empty;
            DateTime nowTime = DateTime.Now;

            while (((TimeSpan)(DateTime.Now - nowTime)).Seconds < 4)
            {
                try
                {
                    recv = newsock.ReceiveFrom(data, ref Remote);
                }
                catch
                {
                    MessageBox.Show("未见有服务器启动,请与管理员联系", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    newsock.Close();

                    return list;

                }
                string strData = Encoding.ASCII.GetString(data, 0, recv);

                strTemp = list.Find(delegate(string a)
                {
                    if (a.Equals(strData))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                });
                if (strTemp == null)
                {
                    list.Add(strData);
                }
            }
            cmbServer.Text = "服务器已刷新,请下拉选择:";
            newsock.Close();
            return list;
        }
        //服务器选择改变
        bool _serverChange = false;
        bool IsNeedReStart = false; //是否需要重启程序
        private void cmbServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            string server = this.cmbServer.SelectedItem.ToString();
            if (server != string.Empty)
            {
                for (int i = 0; i < _listServer.Count; i++)
                {
                    if (_listServer[i].Contains(server))
                    {
                        ModifyConfig(_listServer[i].Split('|')[0]);
                        CheckIpIsModify(_listServer[i].Split('|')[1]);
                        GetServerInfo(_listServer[i].Split('|')[0]);// 显示用
                        ModifyWCFConfig(_listServer[i].Split('|')[1]);
                        // 显示用
                        if (IsNeedReStart == true)
                        {
                            _serverChange = true;
                            Application.Exit();
                            return;
                        }
                    }
                }
            }
        }

        private void CheckIpIsModify(string serverName)
        {
            int startIndex = serverName.IndexOf("(");
            string ip = serverName.Substring(startIndex + 1, serverName.Length - startIndex-2);
            if (!ConfigurationManager.AppSettings["RemoteIP"].Equals(ip))
            {
                ModifyConfigurationOP.SetConfig("RemoteIP", ip);         
            }
        }

        //刷新数据库服务器
        private void btnReflsh_Click(object sender, EventArgs e)
        {
            btnReflsh.Enabled = false;
            Cursor = Cursors.WaitCursor;
            cmbServer.Properties.Items.Clear();
            _listServer = UDPMessage.GetServerInfo();
            for (int i = 0; i < _listServer.Count; i++)
            {
                this.cmbServer.Properties.Items.Add(_listServer[i].Split('|')[1]);
            }
            Cursor = Cursors.Default;
            btnReflsh.Enabled = true;
        }

        private void FrmLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin.PerformClick();
            }
        }

        private void btnChangePwd_Click(object sender, EventArgs e)
        {
            FrmChangePwd frmChangePwd = FrmChangePwd.GetInstance;
            frmChangePwd.ShowDialog();
        }

        private void FindWindow()
        {
            int isHaveFrm = (int)UtilMethod.FindWindow(null, "角色选择");
            if (isHaveFrm > 0)
            {
                UtilMethod.SetWindowPos(isHaveFrm, -1, 0, 0, Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height, 0x40);//激活登录窗体

                Environment.Exit(0);
            }
        }

        private void tsQuit_Click(object sender, EventArgs e)
        {

        }


        /// <summary>
        /// 修改WCF配置
        /// </summary>
        /// <param name="ip"></param>
        private void ModifyWCFConfig(string ip)
        {
            int startIndex = ip.IndexOf("(");
            string ipaddress = ip.Substring(startIndex + 1, ip.Length - startIndex - 2);
            string configFilePath = Application.StartupPath + "\\MINERP.UserLogin.exe.Config";
            Modify(configFilePath, ipaddress);
        }

        private  static int Modify(string path, string newIP)
        {
            int rtnVal = 0;
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                ConfigurationSectionGroup sct = config.SectionGroups["system.serviceModel"];
                ServiceModelSectionGroup serviceModelSectionGroup = sct as ServiceModelSectionGroup;
                ClientSection clientSection = serviceModelSectionGroup.Client;
                foreach (ChannelEndpointElement item in clientSection.Endpoints)
                {
                    string pattern = "://.*/";
                    string address = item.Address.ToString();
                    string oldHost = item.Address.Host;
                    if (oldHost.Equals(newIP))
                    {
                        rtnVal = 1;//不要改变
                        break;
                    }
                    string replacement = string.Format("://{0}:{1}/{2}/", newIP, 7892, "ServiceImpl");
                    address = Regex.Replace(address, pattern, replacement);
                    item.Address = new Uri(address);
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("system.serviceModel");
            }
            catch (Exception ex)
            {
                rtnVal = -1;
            }
            return rtnVal;
        }


    }
}